#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.prod'

import django
django.setup()

import requests, os, hashlib, datetime, json
from django.db import transaction
from random import randint

from activities.models import Channel
from merchants.models import Merchant, MerchantUser, MerchantImage, MerchantChannel
from users.models import Level
from equity_mall.utils.sync_img_to_local import sync_img_to_local
from vouchers.models import CustomizeActivityPayRulesLimitMerchant
from equity_mall.utils.fulianghui_merchant import Fulianghui_Sign


def add_merchant1():
    file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "business_no1")
    with open(file_path, 'r', encoding='utf-8') as f:
        result = f.readlines()
    for row in result:
        business_no = str(row).replace('\n', '')
        md5 = hashlib.md5()  # 使用MD5加密模式
        md5.update(str(business_no).encode('utf-8'))  # 将参数字符串传入
        sign = md5.hexdigest()  # 完成加密并转为大写
        url = 'https://manage.gdwxyf.com/internal/searchmerchantbyshopids.do'
        body = {
            'account': 'gdyouzheng',
            'shopId': sign
        }
        reaponse = requests.post(url=url, data=body)
        try:
            reaponse = reaponse.json()
        except:
            print(f'{business_no}错误')
            continue
        if 'wx_channel_merchant_id' not in reaponse:
            print(f'{business_no}错误')
            continue
        if reaponse['wx_channel_merchant_id'] == '':
            print(f'{business_no}错误')
            continue
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()
            try:
                merchant_data = {}
                channel_mch_id = reaponse['channel_mch_id']
                channel = Channel.objects.filter(mchid=channel_mch_id).first()
                if channel:
                    merchant_data['channel_id'] = channel.id
                merchant_data['name'] = reaponse['shopName']
                merchant_data['short_name'] = reaponse['shopNickname']
                merchant_data['wyfMerchantID'] = business_no
                merchant_data['ruiyinxinMerchantID'] = sign
                merchant_data['create_time'] = datetime.datetime.now()
                if reaponse['businessType'] == '1':
                    merchant_data['subject_type'] = 3
                elif reaponse['businessType'] == '2':
                    merchant_data['subject_type'] = 2
                elif reaponse['businessType'] == '3':
                    merchant_data['subject_type'] = 1
                else:
                    merchant_data['subject_type'] = 4
                level = Level.objects.filter(acceptId=reaponse['accept_id']).first()
                if level:
                    merchant_data['level_id'] = level.id
                merchantuser, create = MerchantUser.objects.get_or_create(mobile=reaponse['phone'], defaults={"mobile": reaponse['phone']})
                merchant_data['merchantuser_id'] = merchantuser.id
                merchant_data['account_name'] = reaponse['cardName']
                merchant_data['account_bank'] = reaponse['bankName']
                merchant_data['account_number'] = reaponse['card']
                card_copy = f'youhuiquanyi/{business_no}/card_copy.png'
                card_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/cardFace.png', key=card_copy)
                if card_copy_url:
                    merchant_data['card_copy'] = card_copy
                merchant_data['identification_number'] = reaponse['identity']
                merchant_data['store_address'] = reaponse['address']
                store_header_copy = f'youhuiquanyi/{business_no}/store_header_copy.png'
                store_header_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantHead.png', key=store_header_copy)
                if store_header_copy_url:
                    merchant_data['store_header_copy'] = store_header_copy
                merchant, cereate = Merchant.objects.update_or_create(defaults=merchant_data, wyfMerchantID=business_no)
                if not merchant.managerName:
                    merchant.managerName = reaponse['keeper']
                if not merchant.managermobile:
                    merchant.managermobile = reaponse['phone']
                if not merchant.prov_name:
                    merchant.prov_name = reaponse['province']
                    merchant.city_name = reaponse['city']
                    merchant.district_name = reaponse['area']
                if not merchant.business_category:
                    merchant.business_category_id = 1
                if not merchant.store_logo_copy:
                    merchant.store_logo_copy = 'default_merchant_logo.jpg'
                merchant.save()
                if cereate and merchant.channel:
                    store_header_copy = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                    store_header_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantHead.png', key=store_header_copy)
                    if store_header_copy_url:
                        MerchantImage.objects.create(merchant_id=merchant.id, image=store_header_copy)
                    store_indoor_copy = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                    store_indoor_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/otherPhoto3.png', key=store_indoor_copy)
                    if store_indoor_copy_url:
                        MerchantImage.objects.create(merchant_id=merchant.id, image=store_indoor_copy)
                    merchantCheck = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                    merchantCheck_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantCheck.png', key=merchantCheck)
                    if merchantCheck_url:
                        MerchantImage.objects.create(merchant_id=merchant.id, image=merchantCheck)
                merchantchannel_data = {
                    'merchant_id': merchant.id
                }
                if reaponse['allchannelJson']['channel_ruiyinxin']:
                    if reaponse['allchannelJson']['channel_ruiyinxin']['status'] == 1:
                        merchantchannel_data['smid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_4']
                        merchantchannel_data['channel_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_7']
                        merchantchannel_data['channel_id'] = 2
                        merchantchannel_data['sub_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_3']
                        MerchantChannel.objects.get_or_create(defaults=merchantchannel_data, merchant_id=merchant.id, channel_id=merchantchannel_data['channel_id'])
                if reaponse['allchannelJson']['channel_sxf_tq']:
                    if reaponse['allchannelJson']['channel_sxf_tq']['status'] == 1:
                        merchantchannel_data['smid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_other_4'] if 'merchant_other_4' in reaponse['allchannelJson']['channel_sxf_tq'] else ''
                        merchantchannel_data['channel_mchid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_no']
                        merchantchannel_data['channel_id'] = 3
                        merchantchannel_data['sub_mchid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_other_3']
                        MerchantChannel.objects.get_or_create(defaults=merchantchannel_data, merchant_id=merchant.id, channel_id=merchantchannel_data['channel_id'])
                transaction.savepoint_commit(save_id)
                print(f'{business_no}成功')
            except Exception as e:
                print(f'{business_no}错误')
                transaction.savepoint_rollback(save_id)
                continue


def add_merchant2():
    file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "business_no2")
    with open(file_path, 'r', encoding='utf-8') as f:
        result = f.readlines()
    for row in result:
        business_no = str(row).replace('\n', '')
        md5 = hashlib.md5()  # 使用MD5加密模式
        md5.update(str(business_no).encode('utf-8'))  # 将参数字符串传入
        sign = md5.hexdigest()  # 完成加密并转为大写
        url = 'https://manage.gdwxyf.com/internal/searchmerchantbyshopids.do'
        body = {
            'account': 'gdyouzheng',
            'shopId': sign
        }
        reaponse = requests.post(url=url, data=body)
        try:
            reaponse = reaponse.json()
        except:
            print(f'{business_no}错误')
            continue
        if 'wx_channel_merchant_id' not in reaponse:
            print(f'{business_no}错误')
            continue
        if reaponse['wx_channel_merchant_id'] == '':
            print(f'{business_no}错误')
            continue
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()
            try:
                merchant_data = {}
                channel_mch_id = reaponse['channel_mch_id']
                channel = Channel.objects.filter(mchid=channel_mch_id).first()
                if channel:
                    merchant_data['channel_id'] = channel.id
                merchant_data['name'] = reaponse['shopName']
                merchant_data['short_name'] = reaponse['shopNickname']
                merchant_data['wyfMerchantID'] = business_no
                merchant_data['ruiyinxinMerchantID'] = sign
                merchant_data['create_time'] = datetime.datetime.now()
                if reaponse['businessType'] == '1':
                    merchant_data['subject_type'] = 3
                elif reaponse['businessType'] == '2':
                    merchant_data['subject_type'] = 2
                elif reaponse['businessType'] == '3':
                    merchant_data['subject_type'] = 1
                else:
                    merchant_data['subject_type'] = 4
                level = Level.objects.filter(acceptId=reaponse['accept_id']).first()
                if level:
                    merchant_data['level_id'] = level.id
                merchantuser, create = MerchantUser.objects.get_or_create(mobile=reaponse['phone'], defaults={"mobile": reaponse['phone']})
                merchant_data['merchantuser_id'] = merchantuser.id
                merchant_data['account_name'] = reaponse['cardName']
                merchant_data['account_bank'] = reaponse['bankName']
                merchant_data['account_number'] = reaponse['card']
                card_copy = f'youhuiquanyi/{business_no}/card_copy.png'
                card_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/cardFace.png', key=card_copy)
                if card_copy_url:
                    merchant_data['card_copy'] = card_copy
                merchant_data['identification_number'] = reaponse['identity']
                merchant_data['store_address'] = reaponse['address']
                store_header_copy = f'youhuiquanyi/{business_no}/store_header_copy.png'
                store_header_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantHead.png', key=store_header_copy)
                if store_header_copy_url:
                    merchant_data['store_header_copy'] = store_header_copy
                merchant, cereate = Merchant.objects.update_or_create(defaults=merchant_data, wyfMerchantID=business_no)
                if not merchant.managerName:
                    merchant.managerName = reaponse['keeper']
                if not merchant.managermobile:
                    merchant.managermobile = reaponse['phone']
                if not merchant.prov_name:
                    merchant.prov_name = reaponse['province']
                    merchant.city_name = reaponse['city']
                    merchant.district_name = reaponse['area']
                if not merchant.business_category:
                    merchant.business_category_id = 1
                if not merchant.store_logo_copy:
                    merchant.store_logo_copy = 'default_merchant_logo.jpg'
                merchant.save()
                if cereate and merchant.channel:
                    store_header_copy = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                    store_header_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantHead.png', key=store_header_copy)
                    if store_header_copy_url:
                        MerchantImage.objects.create(merchant_id=merchant.id, image=store_header_copy)
                    store_indoor_copy = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                    store_indoor_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/otherPhoto3.png', key=store_indoor_copy)
                    if store_indoor_copy_url:
                        MerchantImage.objects.create(merchant_id=merchant.id, image=store_indoor_copy)
                    merchantCheck = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                    merchantCheck_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantCheck.png', key=merchantCheck)
                    if merchantCheck_url:
                        MerchantImage.objects.create(merchant_id=merchant.id, image=merchantCheck)
                merchantchannel_data = {
                    'merchant_id': merchant.id
                }
                if reaponse['allchannelJson']['channel_ruiyinxin']:
                    if reaponse['allchannelJson']['channel_ruiyinxin']['status'] == 1:
                        merchantchannel_data['smid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_4']
                        merchantchannel_data['channel_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_7']
                        merchantchannel_data['channel_id'] = 2
                        merchantchannel_data['sub_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_3']
                        MerchantChannel.objects.get_or_create(defaults=merchantchannel_data, merchant_id=merchant.id, channel_id=merchantchannel_data['channel_id'])
                if reaponse['allchannelJson']['channel_sxf_tq']:
                    if reaponse['allchannelJson']['channel_sxf_tq']['status'] == 1:
                        merchantchannel_data['smid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_other_4'] if 'merchant_other_4' in reaponse['allchannelJson']['channel_sxf_tq'] else ''
                        merchantchannel_data['channel_mchid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_no']
                        merchantchannel_data['channel_id'] = 3
                        merchantchannel_data['sub_mchid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_other_3']
                        MerchantChannel.objects.get_or_create(defaults=merchantchannel_data, merchant_id=merchant.id, channel_id=merchantchannel_data['channel_id'])
                transaction.savepoint_commit(save_id)
                print(f'{business_no}成功')
            except Exception as e:
                print(f'{business_no}错误')
                transaction.savepoint_rollback(save_id)
                continue


def add_merchant3():
    file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "business_no3")
    with open(file_path, 'r', encoding='utf-8') as f:
        result = f.readlines()
    for row in result:
        business_no = str(row).replace('\n', '')
        md5 = hashlib.md5()  # 使用MD5加密模式
        md5.update(str(business_no).encode('utf-8'))  # 将参数字符串传入
        sign = md5.hexdigest()  # 完成加密并转为大写
        url = 'https://manage.gdwxyf.com/internal/searchmerchantbyshopids.do'
        body = {
            'account': 'gdyouzheng',
            'shopId': sign
        }
        reaponse = requests.post(url=url, data=body)
        try:
            reaponse = reaponse.json()
        except:
            print(f'{business_no}错误')
            continue
        if 'wx_channel_merchant_id' not in reaponse:
            print(f'{business_no}错误')
            continue
        if reaponse['wx_channel_merchant_id'] == '':
            print(f'{business_no}错误')
            continue
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()
            try:
                merchant_data = {}
                channel_mch_id = reaponse['channel_mch_id']
                channel = Channel.objects.filter(mchid=channel_mch_id).first()
                if channel:
                    merchant_data['channel_id'] = channel.id
                merchant_data['name'] = reaponse['shopName']
                merchant_data['short_name'] = reaponse['shopNickname']
                merchant_data['wyfMerchantID'] = business_no
                merchant_data['ruiyinxinMerchantID'] = sign
                merchant_data['create_time'] = datetime.datetime.now()
                if reaponse['businessType'] == '1':
                    merchant_data['subject_type'] = 3
                elif reaponse['businessType'] == '2':
                    merchant_data['subject_type'] = 2
                elif reaponse['businessType'] == '3':
                    merchant_data['subject_type'] = 1
                else:
                    merchant_data['subject_type'] = 4
                level = Level.objects.filter(acceptId=reaponse['accept_id']).first()
                if level:
                    merchant_data['level_id'] = level.id
                merchantuser, create = MerchantUser.objects.get_or_create(mobile=reaponse['phone'], defaults={"mobile": reaponse['phone']})
                merchant_data['merchantuser_id'] = merchantuser.id
                merchant_data['account_name'] = reaponse['cardName']
                merchant_data['account_bank'] = reaponse['bankName']
                merchant_data['account_number'] = reaponse['card']
                card_copy = f'youhuiquanyi/{business_no}/card_copy.png'
                card_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/cardFace.png', key=card_copy)
                if card_copy_url:
                    merchant_data['card_copy'] = card_copy
                merchant_data['identification_number'] = reaponse['identity']
                merchant_data['store_address'] = reaponse['address']
                store_header_copy = f'youhuiquanyi/{business_no}/store_header_copy.png'
                store_header_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantHead.png', key=store_header_copy)
                if store_header_copy_url:
                    merchant_data['store_header_copy'] = store_header_copy
                merchant, cereate = Merchant.objects.update_or_create(defaults=merchant_data, wyfMerchantID=business_no)
                if not merchant.managerName:
                    merchant.managerName = reaponse['keeper']
                if not merchant.managermobile:
                    merchant.managermobile = reaponse['phone']
                if not merchant.prov_name:
                    merchant.prov_name = reaponse['province']
                    merchant.city_name = reaponse['city']
                    merchant.district_name = reaponse['area']
                if not merchant.business_category:
                    merchant.business_category_id = 1
                if not merchant.store_logo_copy:
                    merchant.store_logo_copy = 'default_merchant_logo.jpg'
                merchant.save()
                if cereate and merchant.channel:
                    store_header_copy = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                    store_header_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantHead.png', key=store_header_copy)
                    if store_header_copy_url:
                        MerchantImage.objects.create(merchant_id=merchant.id, image=store_header_copy)
                    store_indoor_copy = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                    store_indoor_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/otherPhoto3.png', key=store_indoor_copy)
                    if store_indoor_copy_url:
                        MerchantImage.objects.create(merchant_id=merchant.id, image=store_indoor_copy)
                    merchantCheck = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                    merchantCheck_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantCheck.png', key=merchantCheck)
                    if merchantCheck_url:
                        MerchantImage.objects.create(merchant_id=merchant.id, image=merchantCheck)
                merchantchannel_data = {
                    'merchant_id': merchant.id
                }
                if reaponse['allchannelJson']['channel_ruiyinxin']:
                    if reaponse['allchannelJson']['channel_ruiyinxin']['status'] == 1:
                        merchantchannel_data['smid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_4']
                        merchantchannel_data['channel_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_7']
                        merchantchannel_data['channel_id'] = 2
                        merchantchannel_data['sub_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_3']
                        MerchantChannel.objects.get_or_create(defaults=merchantchannel_data, merchant_id=merchant.id, channel_id=merchantchannel_data['channel_id'])
                if reaponse['allchannelJson']['channel_sxf_tq']:
                    if reaponse['allchannelJson']['channel_sxf_tq']['status'] == 1:
                        merchantchannel_data['smid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_other_4'] if 'merchant_other_4' in reaponse['allchannelJson']['channel_sxf_tq'] else ''
                        merchantchannel_data['channel_mchid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_no']
                        merchantchannel_data['channel_id'] = 3
                        merchantchannel_data['sub_mchid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_other_3']
                        MerchantChannel.objects.get_or_create(defaults=merchantchannel_data, merchant_id=merchant.id, channel_id=merchantchannel_data['channel_id'])
                transaction.savepoint_commit(save_id)
                print(f'{business_no}成功')
            except Exception as e:
                print(f'{business_no}错误')
                transaction.savepoint_rollback(save_id)
                continue


def add_merchant():
    app_id = "internal-00001"
    key = "DMN#%2XCu2nxns8rmy^qmrk1g4fK#BKn"
    today = datetime.datetime.now()
    yesterday = today + datetime.timedelta(days=-1)
    start = datetime.datetime.strptime(yesterday.strftime("%Y-%m-%d 00:00:00"), "%Y-%m-%d %H:%M:%S")
    url1 = 'https://manage.gdwxyf.com/internal/searchmerchant.do'
    while True:
        print(start.strftime("%Y-%m-%d %H:%M:%S"))
        if start >= today:
            break
        end = start + datetime.timedelta(minutes=10)
        body1 = {
            "account": "gdyouzheng",
            "branchId": "2",
            "is_delete": "0",
            "start": start.strftime("%Y-%m-%d %H:%M:%S"),
            "end": end.strftime("%Y-%m-%d %H:%M:%S"),
            "shopId": "",
        }
        response = requests.post(url=url1, data=body1)
        result = json.loads(response.content.decode())['showList']
        start = end
        for i in result:
            business_no = i['shop_account']
            check_merchant = Merchant.objects.filter(wyfMerchantID=business_no)
            if check_merchant:
                continue
            md5 = hashlib.md5()  # 使用MD5加密模式
            md5.update(str(business_no).encode('utf-8'))  # 将参数字符串传入
            sign = md5.hexdigest()  # 完成加密并转为大写
            url = 'https://manage.gdwxyf.com/internal/searchmerchantbyshopids.do'
            body = {
                'account': 'gdyouzheng',
                'shopId': sign
            }
            reaponse = requests.post(url=url, data=body)
            try:
                reaponse = reaponse.json()
            except:
                print(f'{business_no}错误')
                continue
            if 'wx_channel_merchant_id' not in reaponse:
                print(f'{business_no}错误')
                continue
            if reaponse['wx_channel_merchant_id'] == '':
                print(f'{business_no}错误')
                continue
            with transaction.atomic():
                # 创建事务保存点
                save_id = transaction.savepoint()
                try:
                    merchant_data = {}
                    channel_mch_id = reaponse['channel_mch_id']
                    channel = Channel.objects.filter(mchid=channel_mch_id).first()
                    if channel:
                        merchant_data['channel_id'] = channel.id
                    merchant_data['name'] = reaponse['shopName']
                    merchant_data['short_name'] = reaponse['shopNickname']
                    merchant_data['wyfMerchantID'] = business_no
                    merchant_data['ruiyinxinMerchantID'] = sign
                    merchant_data['create_time'] = datetime.datetime.now()
                    if reaponse['businessType'] == '1':
                        merchant_data['subject_type'] = 3
                    elif reaponse['businessType'] == '2':
                        merchant_data['subject_type'] = 2
                    elif reaponse['businessType'] == '3':
                        merchant_data['subject_type'] = 1
                    else:
                        merchant_data['subject_type'] = 4
                    level = Level.objects.filter(acceptId=reaponse['accept_id']).first()
                    if level:
                        merchant_data['level_id'] = level.id
                    merchantuser, create = MerchantUser.objects.get_or_create(mobile=reaponse['phone'], defaults={"mobile": reaponse['phone'], 'level_id': level.id if level else None})
                    merchant_data['merchantuser_id'] = merchantuser.id
                    merchant_data['account_name'] = reaponse['cardName']
                    merchant_data['account_bank'] = reaponse['bankName']
                    merchant_data['account_number'] = reaponse['card']
                    card_copy = f'youhuiquanyi/{business_no}/card_copy.png'
                    card_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/cardFace.png',
                                                      key=card_copy)
                    if card_copy_url:
                        merchant_data['card_copy'] = card_copy
                    merchant_data['identification_number'] = reaponse['identity']
                    merchant_data['store_address'] = reaponse['address']
                    store_header_copy = f'youhuiquanyi/{business_no}/store_header_copy.png'
                    store_header_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantHead.png',
                                                              key=store_header_copy)
                    if store_header_copy_url:
                        merchant_data['store_header_copy'] = store_header_copy
                    if 'latitude' in reaponse:
                        merchant_data['latitude'] = reaponse['latitude']
                    if 'longitude' in reaponse:
                        merchant_data['longitude'] = reaponse['longitude']
                    merchant, cereate = Merchant.objects.update_or_create(defaults=merchant_data,
                                                                          wyfMerchantID=business_no)
                    if not merchant.managerName:
                        merchant.managerName = reaponse['keeper']
                    if not merchant.managermobile:
                        merchant.managermobile = reaponse['phone']
                    if not merchant.prov_name:
                        merchant.prov_name = reaponse['province']
                        merchant.city_name = reaponse['city']
                        merchant.district_name = reaponse['area']
                    if not merchant.business_category:
                        merchant.business_category_id = 1
                    if not merchant.store_logo_copy:
                        merchant.store_logo_copy = 'default_merchant_logo.jpg'
                    merchant.save()
                    if cereate and merchant.channel:
                        store_header_copy = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                        store_header_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantHead.png', key=store_header_copy)
                        if store_header_copy_url:
                            MerchantImage.objects.create(merchant_id=merchant.id, image=store_header_copy)
                        store_indoor_copy = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                        store_indoor_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/otherPhoto3.png', key=store_indoor_copy)
                        if store_indoor_copy_url:
                            MerchantImage.objects.create(merchant_id=merchant.id, image=store_indoor_copy)
                        merchantCheck = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                        merchantCheck_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantCheck.png', key=merchantCheck)
                        if merchantCheck_url:
                            MerchantImage.objects.create(merchant_id=merchant.id, image=merchantCheck)
                    merchantchannel_data = {
                        'merchant_id': merchant.id
                    }
                    if reaponse['allchannelJson']['channel_ruiyinxin']:
                        if reaponse['allchannelJson']['channel_ruiyinxin']['status'] == 1:
                            merchantchannel_data['smid'] = reaponse['allchannelJson']['channel_ruiyinxin'][
                                'merchant_other_4']
                            merchantchannel_data['channel_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin'][
                                'merchant_other_7']
                            merchantchannel_data['channel_id'] = 2
                            merchantchannel_data['sub_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin'][
                                'merchant_other_3']
                            MerchantChannel.objects.get_or_create(defaults=merchantchannel_data,
                                                                  merchant_id=merchant.id,
                                                                  channel_id=merchantchannel_data['channel_id'])
                    if reaponse['allchannelJson']['channel_sxf_tq']:
                        if reaponse['allchannelJson']['channel_sxf_tq']['status'] == 1:
                            merchantchannel_data['smid'] = reaponse['allchannelJson']['channel_sxf_tq'][
                                'merchant_other_4'] if 'merchant_other_4' in reaponse['allchannelJson'][
                                'channel_sxf_tq'] else ''
                            merchantchannel_data['channel_mchid'] = reaponse['allchannelJson']['channel_sxf_tq'][
                                'merchant_no']
                            merchantchannel_data['channel_id'] = 3
                            merchantchannel_data['sub_mchid'] = reaponse['allchannelJson']['channel_sxf_tq'][
                                'merchant_other_3']
                            MerchantChannel.objects.get_or_create(defaults=merchantchannel_data,
                                                                  merchant_id=merchant.id,
                                                                  channel_id=merchantchannel_data['channel_id'])
                    if reaponse['channel_mch_id'] == '227823797':
                        try:
                            channel_url = 'https://manage.gdwxyf.com/internal/searchmerchantchannelmsg.do'
                            channel_body = {"account": "gdyouzheng", "shopId": sign}
                            channel_response = requests.post(url=channel_url, data=channel_body)
                            channel_result = channel_response.json()
                            merchantchannel_data['smid'] = channel_result['alipaychannelJson']['merchant_other_4'] if 'merchant_other_4' in channel_result['alipaychannelJson'] else ''
                            merchantchannel_data['channel_mchid'] = channel_result['alipaychannelJson']['upMerchantNo']
                            merchantchannel_data['channel_id'] = 15
                            merchantchannel_data['sub_mchid'] = channel_result['wxchannelJson']['merchant_other_3']
                            MerchantChannel.objects.get_or_create(defaults=merchantchannel_data, merchant_id=merchant.id, channel_id=merchantchannel_data['channel_id'])
                        except:
                            pass
                    transaction.savepoint_commit(save_id)
                    print(f'{business_no}成功')
                except Exception as e:
                    print(f'{business_no}错误')
                    transaction.savepoint_rollback(save_id)
                    continue
                try:
                    fulianguhui_data = {}
                    fulianguhui_data['openid'] = business_no
                    fulianguhui_data['merchant_name'] = reaponse['shopName']
                    fulianguhui_data['address'] = reaponse['address']
                    fulianguhui_data['longitude'] = reaponse['longitude'] if 'longitude' in reaponse else ''
                    fulianguhui_data['latitude'] = reaponse['latitude'] if 'latitude' in reaponse else ''
                    fulianguhui_data['org_id'] = reaponse['accept_id']
                    request_data = Fulianghui_Sign(app_id, key).request_data(fulianguhui_data)
                    flh_response = requests.post(url='https://apiad.sutpay.com/adapi/external/update_merchant/', data=json.dumps(request_data), headers={"Content-Type": "application/json"})
                    print(flh_response.json())
                except:
                    pass


def add_merchant_shanxi():
    app_id = "internal-00001"
    key = "DMN#%2XCu2nxns8rmy^qmrk1g4fK#BKn"
    today = datetime.datetime.now()
    yesterday = today + datetime.timedelta(days=-1)
    start = datetime.datetime.strptime(yesterday.strftime("%Y-%m-%d 00:00:00"), "%Y-%m-%d %H:%M:%S")
    url1 = 'https://manage.gdwxyf.com/internal/searchmerchant.do'
    while True:
        print(start.strftime("%Y-%m-%d %H:%M:%S"))
        if start >= today:
            break
        end = start + datetime.timedelta(minutes=10)
        body1 = {
            "account": "gdyouzheng",
            "branchId": "6",
            "is_delete": "0",
            "start": start.strftime("%Y-%m-%d %H:%M:%S"),
            "end": end.strftime("%Y-%m-%d %H:%M:%S"),
            "shopId": "",
        }
        response = requests.post(url=url1, data=body1)
        result = json.loads(response.content.decode())['showList']
        start = end
        for i in result:
            business_no = i['shop_account']
            check_merchant = Merchant.objects.filter(wyfMerchantID=business_no)
            if check_merchant:
                continue
            md5 = hashlib.md5()  # 使用MD5加密模式
            md5.update(str(business_no).encode('utf-8'))  # 将参数字符串传入
            sign = md5.hexdigest()  # 完成加密并转为大写
            url = 'https://manage.gdwxyf.com/internal/searchmerchantbyshopids.do'
            body = {
                'account': 'gdyouzheng',
                'shopId': sign
            }
            reaponse = requests.post(url=url, data=body)
            try:
                reaponse = reaponse.json()
            except:
                print(f'{business_no}错误')
                continue
            if 'wx_channel_merchant_id' not in reaponse:
                print(f'{business_no}错误')
                continue
            if reaponse['wx_channel_merchant_id'] == '':
                print(f'{business_no}错误')
                continue
            with transaction.atomic():
                # 创建事务保存点
                save_id = transaction.savepoint()
                try:
                    merchant_data = {}
                    channel_mch_id = reaponse['channel_mch_id']
                    channel = Channel.objects.filter(mchid=channel_mch_id).first()
                    if channel:
                        merchant_data['channel_id'] = channel.id
                    merchant_data['name'] = reaponse['shopName']
                    merchant_data['short_name'] = reaponse['shopNickname']
                    merchant_data['wyfMerchantID'] = business_no
                    merchant_data['ruiyinxinMerchantID'] = sign
                    merchant_data['create_time'] = datetime.datetime.now()
                    if reaponse['businessType'] == '1':
                        merchant_data['subject_type'] = 3
                    elif reaponse['businessType'] == '2':
                        merchant_data['subject_type'] = 2
                    elif reaponse['businessType'] == '3':
                        merchant_data['subject_type'] = 1
                    else:
                        merchant_data['subject_type'] = 4
                    level = Level.objects.filter(acceptId=reaponse['accept_id']).first()
                    if level:
                        merchant_data['level_id'] = level.id
                    merchantuser, create = MerchantUser.objects.get_or_create(mobile=reaponse['phone'], defaults={"mobile": reaponse['phone'], 'level_id': level.id if level else None})
                    merchant_data['merchantuser_id'] = merchantuser.id
                    merchant_data['account_name'] = reaponse['cardName']
                    merchant_data['account_bank'] = reaponse['bankName']
                    merchant_data['account_number'] = reaponse['card']
                    card_copy = f'youhuiquanyi/{business_no}/card_copy.png'
                    card_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/cardFace.png',
                                                      key=card_copy)
                    if card_copy_url:
                        merchant_data['card_copy'] = card_copy
                    merchant_data['identification_number'] = reaponse['identity']
                    merchant_data['store_address'] = reaponse['address']
                    store_header_copy = f'youhuiquanyi/{business_no}/store_header_copy.png'
                    store_header_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantHead.png',
                                                              key=store_header_copy)
                    if store_header_copy_url:
                        merchant_data['store_header_copy'] = store_header_copy
                    if 'latitude' in reaponse:
                        merchant_data['latitude'] = reaponse['latitude']
                    if 'longitude' in reaponse:
                        merchant_data['longitude'] = reaponse['longitude']
                    merchant, cereate = Merchant.objects.update_or_create(defaults=merchant_data,
                                                                          wyfMerchantID=business_no)
                    if not merchant.managerName:
                        merchant.managerName = reaponse['keeper']
                    if not merchant.managermobile:
                        merchant.managermobile = reaponse['phone']
                    if not merchant.prov_name:
                        merchant.prov_name = reaponse['province']
                        merchant.city_name = reaponse['city']
                        merchant.district_name = reaponse['area']
                    if not merchant.business_category:
                        merchant.business_category_id = 1
                    if not merchant.store_logo_copy:
                        merchant.store_logo_copy = 'default_merchant_logo.jpg'
                    merchant.save()
                    if cereate and merchant.channel:
                        store_header_copy = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                        store_header_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantHead.png', key=store_header_copy)
                        if store_header_copy_url:
                            MerchantImage.objects.create(merchant_id=merchant.id, image=store_header_copy)
                        store_indoor_copy = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                        store_indoor_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/otherPhoto3.png', key=store_indoor_copy)
                        if store_indoor_copy_url:
                            MerchantImage.objects.create(merchant_id=merchant.id, image=store_indoor_copy)
                        merchantCheck = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                        merchantCheck_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantCheck.png', key=merchantCheck)
                        if merchantCheck_url:
                            MerchantImage.objects.create(merchant_id=merchant.id, image=merchantCheck)
                    merchantchannel_data = {
                        'merchant_id': merchant.id
                    }
                    if reaponse['allchannelJson']['channel_ruiyinxin']:
                        if reaponse['allchannelJson']['channel_ruiyinxin']['status'] == 1:
                            merchantchannel_data['smid'] = reaponse['allchannelJson']['channel_ruiyinxin'][
                                'merchant_other_4']
                            merchantchannel_data['channel_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin'][
                                'merchant_other_7']
                            merchantchannel_data['channel_id'] = 2
                            merchantchannel_data['sub_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin'][
                                'merchant_other_3']
                            MerchantChannel.objects.get_or_create(defaults=merchantchannel_data,
                                                                  merchant_id=merchant.id,
                                                                  channel_id=merchantchannel_data['channel_id'])
                    if reaponse['allchannelJson']['channel_sxf_tq']:
                        if reaponse['allchannelJson']['channel_sxf_tq']['status'] == 1:
                            merchantchannel_data['smid'] = reaponse['allchannelJson']['channel_sxf_tq'][
                                'merchant_other_4'] if 'merchant_other_4' in reaponse['allchannelJson'][
                                'channel_sxf_tq'] else ''
                            merchantchannel_data['channel_mchid'] = reaponse['allchannelJson']['channel_sxf_tq'][
                                'merchant_no']
                            merchantchannel_data['channel_id'] = 3
                            merchantchannel_data['sub_mchid'] = reaponse['allchannelJson']['channel_sxf_tq'][
                                'merchant_other_3']
                            MerchantChannel.objects.get_or_create(defaults=merchantchannel_data,
                                                                  merchant_id=merchant.id,
                                                                  channel_id=merchantchannel_data['channel_id'])
                    transaction.savepoint_commit(save_id)
                    print(f'{business_no}成功')
                except Exception as e:
                    print(f'{business_no}错误')
                    transaction.savepoint_rollback(save_id)
                    continue
                # try:
                #     fulianguhui_data = {}
                #     fulianguhui_data['openid'] = business_no
                #     fulianguhui_data['merchant_name'] = reaponse['shopName']
                #     fulianguhui_data['address'] = reaponse['address']
                #     fulianguhui_data['longitude'] = reaponse['longitude'] if 'longitude' in reaponse else ''
                #     fulianguhui_data['latitude'] = reaponse['latitude'] if 'latitude' in reaponse else ''
                #     fulianguhui_data['org_id'] = reaponse['accept_id']
                #     request_data = Fulianghui_Sign(app_id, key).request_data(fulianguhui_data)
                #     flh_response = requests.post(url='https://apiad.sutpay.com/adapi/external/update_merchant/', data=json.dumps(request_data), headers={"Content-Type": "application/json"})
                #     print(flh_response.json())
                # except:
                #     pass


def update_merchant_info():
    # merchant_id_list = CustomizeActivityPayRulesLimitMerchant.objects.values_list('merchant_id', flat=True)
    queryset = Merchant.objects.filter(latitude__isnull=True)[:100000]
    print(len(queryset))
    for merchant in queryset:
        keyword = merchant.store_address #.replace(assist_prove.shen_name, '').replace(assist_prove.shi_name, '').replace(assist_prove.xian_name, '').replace('省', '')
        region = merchant.district_name
        # url = f'https://apis.map.qq.com/ws/place/v1/search?keyword={keyword}&boundary=region({region},0)&page_size=9&page_index=1&key=TV7BZ-AZDW4-4Y5UQ-FWV4T-R7NVE-UWFZV'
        url = f'https://apis.map.qq.com/ws/geocoder/v1/?address={keyword}&key=TV7BZ-AZDW4-4Y5UQ-FWV4T-R7NVE-UWFZV'
        response = requests.get(url=url)
        result = response.json()
        if 'result' in result:
            try:
                data = result['result']
                lat = data['location']['lat']
                lng = data['location']['lng']
                merchant.latitude = lat
                merchant.longitude = lng
                merchant.save()
                print(f'{merchant.name}成功')
            except:
                print(f'{merchant.name}失败')
        else:
            merchant.latitude = ''
            merchant.longitude = ''
            merchant.save()
            print(f'{merchant.name}不存在')


def add_merchant_info(business_no):
    business_no = str(business_no).replace(' ', '')
    md5 = hashlib.md5()  # 使用MD5加密模式
    md5.update(str(business_no).encode('utf-8'))  # 将参数字符串传入
    sign = md5.hexdigest()  # 完成加密并转为大写
    url = 'https://manage.gdwxyf.com/internal/searchmerchantbyshopids.do'
    body = {
        'account': 'gdyouzheng',
        'shopId': sign
    }
    reaponse = requests.post(url=url, data=body)
    try:
        reaponse = reaponse.json()
    except:
        print(f'商户号:{business_no},系统繁忙,请重新操作')
        return {'merchant': None}
    if 'wx_channel_merchant_id' not in reaponse:
        print(f'商户号:{business_no},商户号有误,请检查重新操作')
        return {'merchant': None}
    # if reaponse['wx_channel_merchant_id'] == '':
    #     print(f'商户号:{business_no},获取商户信息失败，请确认该商户是否审核成功。')
    #     return {'merchant': None}
    merchant = Merchant.objects.filter(wyfMerchantID=business_no).first()
    if merchant:
        merchantchannel_data = {'merchant_id': merchant.id}
        if reaponse['allchannelJson']['channel_ruiyinxin']:
            if reaponse['allchannelJson']['channel_ruiyinxin']['status'] == 1:
                merchantchannel_data['smid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_4']
                merchantchannel_data['channel_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_7']
                merchantchannel_data['channel_id'] = 2
                merchantchannel_data['sub_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_3']
                MerchantChannel.objects.get_or_create(defaults=merchantchannel_data, merchant_id=merchant.id, channel_id=merchantchannel_data['channel_id'])
        if reaponse['allchannelJson']['channel_sxf_tq']:
            if reaponse['allchannelJson']['channel_sxf_tq']['status'] == 1:
                merchantchannel_data['smid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_other_4'] if 'merchant_other_4' in reaponse['allchannelJson']['channel_sxf_tq'] else ''
                merchantchannel_data['channel_mchid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_no']
                merchantchannel_data['channel_id'] = 3
                merchantchannel_data['sub_mchid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_other_3']
                MerchantChannel.objects.get_or_create(defaults=merchantchannel_data, merchant_id=merchant.id, channel_id=merchantchannel_data['channel_id'])
        if reaponse['channel_mch_id'] == '227823797':
            try:
                channel_url = 'https://manage.gdwxyf.com/internal/searchmerchantchannelmsg.do'
                channel_body = {"account": "gdyouzheng", "shopId": sign}
                channel_response = requests.post(url=channel_url, data=channel_body)
                channel_result = channel_response.json()
                merchantchannel_data['smid'] = channel_result['alipaychannelJson']['merchant_other_4'] if 'merchant_other_4' in channel_result['alipaychannelJson'] else ''
                merchantchannel_data['channel_mchid'] = channel_result['alipaychannelJson']['upMerchantNo']
                merchantchannel_data['channel_id'] = 15
                merchantchannel_data['sub_mchid'] = channel_result['wxchannelJson']['merchant_other_3']
                MerchantChannel.objects.get_or_create(defaults=merchantchannel_data, merchant_id=merchant.id, channel_id=merchantchannel_data['channel_id'])
            except:
                pass
    else:
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()
            try:
                merchant_data = {}
                channel_mch_id = reaponse['channel_mch_id']
                channel = Channel.objects.filter(mchid=channel_mch_id).first()
                if channel:
                    merchant_data['channel_id'] = channel.id
                merchant_data['name'] = reaponse['shopName']
                merchant_data['short_name'] = reaponse['shopNickname']
                merchant_data['wyfMerchantID'] = business_no
                merchant_data['ruiyinxinMerchantID'] = sign
                merchant_data['create_time'] = datetime.datetime.now()
                if reaponse['businessType'] == '1':
                    merchant_data['subject_type'] = 3
                elif reaponse['businessType'] == '2':
                    merchant_data['subject_type'] = 2
                elif reaponse['businessType'] == '3':
                    merchant_data['subject_type'] = 1
                else:
                    merchant_data['subject_type'] = 4
                level = Level.objects.filter(acceptId=reaponse['accept_id']).first()
                if level:
                    merchant_data['level_id'] = level.id
                merchantuser, create = MerchantUser.objects.get_or_create(mobile=reaponse['phone'], defaults={"mobile": reaponse['phone'], 'level_id': level.id if level else None})
                merchant_data['merchantuser_id'] = merchantuser.id
                merchant_data['account_name'] = reaponse['cardName']
                merchant_data['account_bank'] = reaponse['bankName']
                merchant_data['account_number'] = reaponse['card']
                if 'latitude' in reaponse:
                    merchant_data['latitude'] = reaponse['latitude']
                if 'longitude' in reaponse:
                    merchant_data['longitude'] = reaponse['longitude']
                card_copy = f'youhuiquanyi/{business_no}/card_copy.png'
                card_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/cardFace.png', key=card_copy)
                if card_copy_url:
                    merchant_data['card_copy'] = card_copy
                merchant_data['identification_number'] = reaponse['identity']
                merchant_data['store_address'] = reaponse['address']
                store_header_copy = f'youhuiquanyi/{business_no}/store_header_copy.png'
                store_header_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantHead.png', key=store_header_copy)
                if store_header_copy_url:
                    merchant_data['store_header_copy'] = store_header_copy
                merchant, cereate = Merchant.objects.update_or_create(defaults=merchant_data, wyfMerchantID=business_no)
                if not merchant.managerName:
                    merchant.managerName = reaponse['keeper']
                if not merchant.managermobile:
                    merchant.managermobile = reaponse['phone']
                if not merchant.prov_name:
                    merchant.prov_name = reaponse['province']
                    merchant.city_name = reaponse['city']
                    merchant.district_name = reaponse['area']
                if not merchant.business_category:
                    merchant.business_category_id = 1
                if not merchant.store_logo_copy:
                    merchant.store_logo_copy = 'default_merchant_logo.jpg'
                merchant.save()
                if cereate and merchant.channel:
                    store_header_copy = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                    store_header_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantHead.png', key=store_header_copy)
                    if store_header_copy_url:
                        MerchantImage.objects.create(merchant_id=merchant.id, image=store_header_copy)
                    store_indoor_copy = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                    store_indoor_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/otherPhoto3.png', key=store_indoor_copy)
                    if store_indoor_copy_url:
                        MerchantImage.objects.create(merchant_id=merchant.id, image=store_indoor_copy)
                    merchantCheck = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                    merchantCheck_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantCheck.png', key=merchantCheck)
                    if merchantCheck_url:
                        MerchantImage.objects.create(merchant_id=merchant.id, image=merchantCheck)
                merchantchannel_data = {
                    'merchant_id': merchant.id
                }
                if reaponse['allchannelJson']['channel_ruiyinxin']:
                    if reaponse['allchannelJson']['channel_ruiyinxin']['status'] == 1:
                        merchantchannel_data['smid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_4']
                        merchantchannel_data['channel_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_7']
                        merchantchannel_data['channel_id'] = 2
                        merchantchannel_data['sub_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_3']
                        MerchantChannel.objects.get_or_create(defaults=merchantchannel_data, merchant_id=merchant.id, channel_id=merchantchannel_data['channel_id'])
                if reaponse['allchannelJson']['channel_sxf_tq']:
                    if reaponse['allchannelJson']['channel_sxf_tq']['status'] == 1:
                        merchantchannel_data['smid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_other_4'] if 'merchant_other_4' in reaponse['allchannelJson']['channel_sxf_tq'] else ''
                        merchantchannel_data['channel_mchid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_no']
                        merchantchannel_data['channel_id'] = 3
                        merchantchannel_data['sub_mchid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_other_3']
                        MerchantChannel.objects.get_or_create(defaults=merchantchannel_data, merchant_id=merchant.id, channel_id=merchantchannel_data['channel_id'])
                transaction.savepoint_commit(save_id)
                print(f'商户号:{business_no},添加成功')
                return {'merchant': merchant}
            except Exception as e:
                transaction.savepoint_rollback(save_id)
                print(f'商户号:{business_no},获取商户信息错误,请联系管理员')
                return {'merchant': None}


if __name__ == '__main__':
    add_merchant_info(6071560045)